package org.hxzon.util;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.commons.io.FileUtils;

import de.innosystec.unrar.Archive;
import de.innosystec.unrar.rarfile.FileHeader;

public class UnrarUtil {
    public static File unrar(String outputDirectory, String inputFilepath) {
        try {
            File outFile = new File(outputDirectory);
            if (!outFile.exists()) {
                outFile.mkdirs();
            }
            Archive archive = new Archive(new File(inputFilepath), null, false);
            FileHeader fileHeader = archive.nextFileHeader();
            while (fileHeader != null) {
                String fileName = fileHeader.getFileNameString();
                if (!fileHeader.isDirectory()) {
                    FileOutputStream out = FileUtils.openOutputStream(new File(outputDirectory + "/" + fileName));
                    archive.extractFile(fileHeader, out);
                    out.close();
                }
                fileHeader = archive.nextFileHeader();
            }
            archive.close();
            return outFile;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static File unrar(String inputFileName) {
        int index = inputFileName.lastIndexOf(".");
        String outputDirectory = inputFileName.substring(0, index);
        return unrar(outputDirectory, inputFileName);
    }

    public static void main(String args[]) {
        UnrarUtil.unrar("D:/java-lib/java-unrar-decryption-supported-src-20120903/rar/test1.rar");
    }
}
